package com.nidu.demo.log.gatewayimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.PageQuery;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nidu.demo.log.convertor.ApiAccessLogConvertor;
import com.nidu.demo.log.gateway.ApiAccessLogGateway;
import com.nidu.demo.log.mapper.ApiAccessLogMapper;
import com.nidu.demo.log.mapper.dataobject.ApiAccessLogDO;
import com.nidu.demo.log.model.ApiAccessLog;
import com.nidu.demo.log.model.ApiAccessLogCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * API访问日志网关实现
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class ApiAccessLogGatewayImpl implements ApiAccessLogGateway {

    private final ApiAccessLogMapper mapper;
    private final ApiAccessLogConvertor convertor;

    @Override
    public ApiAccessLog create(ApiAccessLog apiAccessLog) {
        ApiAccessLogDO apiAccessLogDO = convertor.toDataObject(apiAccessLog);
        mapper.insert(apiAccessLogDO);
        return convertor.toDomainObject(apiAccessLogDO);
    }

    @Override
    public ApiAccessLog update(ApiAccessLog apiAccessLog) {
        ApiAccessLogDO apiAccessLogDO = convertor.toDataObject(apiAccessLog);
        mapper.updateById(apiAccessLogDO);
        return convertor.toDomainObject(apiAccessLogDO);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        mapper.deleteByIds(ids);
    }

    @Override
    public ApiAccessLog getById(Long id) {
        ApiAccessLogDO apiAccessLogDO = mapper.selectById(id);
        if (apiAccessLogDO == null) {
            return null;
        }
        return convertor.toDomainObject(apiAccessLogDO);
    }

    @Override
    public List<ApiAccessLog> getByIds(Set<Long> ids) {
        LambdaQueryWrapper<ApiAccessLogDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ApiAccessLogDO::getId, ids);
        List<ApiAccessLogDO> apiAccessLogDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(apiAccessLogDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(apiAccessLogDOS);
    }

    @Override
    public List<ApiAccessLog> listByCondition(ApiAccessLogCriteria criteria) {
        LambdaQueryWrapper<ApiAccessLogDO> wrapper = buildQueryWrapper(criteria);
        List<ApiAccessLogDO> apiAccessLogDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(apiAccessLogDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(apiAccessLogDOS);
    }

    @Override
    public PageResponse<ApiAccessLog> pageByCondition(ApiAccessLogCriteria criteria) {
        // 创建查询条件
        LambdaQueryWrapper<ApiAccessLogDO> wrapper = buildQueryWrapper(criteria);

        // 创建分页对象
        Page<ApiAccessLogDO> page = new Page<>(criteria.getPageIndex(), criteria.getPageSize());

        // 排序字段
        if (!StrUtil.isEmpty(criteria.getOrderBy())) {
            if (PageQuery.DESC.equals(criteria.getOrderDirection())) {
                page.addOrder(OrderItem.desc(criteria.getOrderBy()));
            } else {
                page.addOrder(OrderItem.asc(criteria.getOrderBy()));
            }
        }

        // 执行分页查询
        mapper.selectPage(page, wrapper);
        List<ApiAccessLog> apiAccessLogs = convertor.toDomainObjects(page.getRecords());
        return PageResponse.of(apiAccessLogs, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    public void deleteAll() {
        mapper.deleteAll();
    }

    private LambdaQueryWrapper<ApiAccessLogDO> buildQueryWrapper(ApiAccessLogCriteria criteria) {
        LambdaQueryWrapper<ApiAccessLogDO> wrapper = new LambdaQueryWrapper<>();
        
        // 时间范围条件
        LocalDateTime[] createTime = criteria.getCreateTime();
        if (createTime != null) {
            if (createTime.length == 1 && createTime[0] != null) {
                wrapper.ge(ApiAccessLogDO::getCreateTime, createTime[0]);
            } else if (createTime.length > 1 && createTime[0] != null && createTime[1] != null) {
                wrapper.between(ApiAccessLogDO::getCreateTime, createTime[0], createTime[1]);
            }
        }
        
        // 开始时间范围条件
        LocalDateTime[] beginTime = criteria.getBeginTime();
        if (beginTime != null) {
            if (beginTime.length == 1 && beginTime[0] != null) {
                wrapper.ge(ApiAccessLogDO::getBeginTime, beginTime[0]);
            } else if (beginTime.length > 1 && beginTime[0] != null && beginTime[1] != null) {
                wrapper.between(ApiAccessLogDO::getBeginTime, beginTime[0], beginTime[1]);
            }
        }
        
        // 精确查询条件
        wrapper.eq(criteria.getUserId() != null, ApiAccessLogDO::getUserId, criteria.getUserId());
        wrapper.eq(criteria.getApplicationName() != null, ApiAccessLogDO::getApplicationName, criteria.getApplicationName());

        // 模糊查询条件
        wrapper.like(!StrUtil.isEmpty(criteria.getRequestUrl()), ApiAccessLogDO::getRequestUrl, criteria.getRequestUrl());

        return wrapper;
    }

}
